package com.money.activemq;

import com.money.demo.common.Constants;
import com.money.demo.object.MoneyBag;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ScheduledMessage;

import javax.jms.*;
import java.util.List;

public class MQProducer {

    private static Connection connection;
    private static Session session;

    static {
        try {
            //1.创建ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(Constants.MQ_URL);
            //2.创建Connection
            connection = connectionFactory.createConnection();
            //3.启动连接
            connection.start();
            //4.创建会话
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace();
        }


    }


    public static void produce(String name, List<MoneyBag> bags) throws JMSException {
        //5.创建一个目标
        Destination destination = session.createQueue(name);
        //6.创建一个生产者
        MessageProducer producer = session.createProducer(destination);

        for (MoneyBag bag : bags) {
            //7.创建消息
            ObjectMessage message=session.createObjectMessage(bag);
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 3*60*1000);//延迟时间,毫秒
            //8.发布消息
            producer.send(message);
        }

        //9.关闭连接
//        connection.close();
    }

}
